import { ADMIN_MEMBER } from '../actionTypes';
import fetch from '../utils/fetch';
import config from '../config';
import { message } from 'antd';
import * as R from 'ramda';

export const update = (payload) => ({
  type: ADMIN_MEMBER,
  payload,
});

export const openModal = (record) => update({
  modalShow: true,
  modalId: record.id,
  modalName: record.username,
  modalContent: record.info,
});

export const hideModal = (id) => update({
  modalShow: false,
  modalId: '',
  modalContent: '',
});

export const updateModalContent = (modalContent) => update({
  modalContent,
});

export const getAll = () => async (dispatch, getState) => {

  const res = await fetch({
    method: 'GET',
    url: `${config.host}/api/member/all`,
    headers: {
      // authorization: token,
    }
  }).catch(ex => console.error(ex));
  if (res.code === 200) {
    dispatch(update({ data: res.data }));
  } else {
    message.error('网络服务异常');
  }
};

/**
 * 插入图片，上传
 */
export const uploadImg = (param) => async (dispatch, getState) => {
  console.log(param);
  const formData = new FormData();
  formData.append('file', param.file);
  const res = await fetch({
    method: 'post',
    url: `${config.host}/api/upload/content`,
    body: formData,
    headers: {},
  });
  if (res.code === 200) {
    param.success({
      url: res.data,
    })
  } else {
    param.error({
      msg: '上传失败.'
    })
  }
};

/**
 * 保存更新
 */
export const save = () => async (dispatch, getState) => {
  const { modalId, data, modalContent } = getState().admin.member;
  console.log(modalId, modalContent);
  if (!modalContent) {
    message.error('请填写内容');
    return false;
  }

  const res = await fetch({
    method: 'POST',
    url: `${config.host}/api/member/info/edit`,
    param: {
      id: modalId,
      info: modalContent,
    },
  }).catch(ex => console.error(ex));
  if (res.code === 200) {
    message.success('修改成功');
    const index = R.findIndex(R.propEq('id', modalId))(data);
    const arr = R.adjust(item => {
      item.info = modalContent;
      return item;
    }, index)(data);
    dispatch(update({
      modalShow: false,
      data: arr,
      modalId: '',
      modalName: '',
      modalContent: '',
    }));
  } else {
    message.error('网络服务异常');
  }
};
